﻿// COPYRIGHT (C) Tom. ALL RIGHTS RESERVED.
// THE AntdUI PROJECT IS AN WINFORM LIBRARY LICENSED UNDER THE Apache-2.0 License.
// LICENSED UNDER THE Apache License, VERSION 2.0 (THE "License")
// YOU MAY NOT USE THIS FILE EXCEPT IN COMPLIANCE WITH THE License.
// YOU MAY OBTAIN A COPY OF THE LICENSE AT
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING, SOFTWARE
// DISTRIBUTED UNDER THE LICENSE IS DISTRIBUTED ON AN "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
// SEE THE LICENSE FOR THE SPECIFIC LANGUAGE GOVERNING PERMISSIONS AND
// LIMITATIONS UNDER THE License.
// GITCODE: https://gitcode.com/AntdUI/AntdUI
// GITEE: https://gitee.com/AntdUI/AntdUI
// GITHUB: https://github.com/AntdUI/AntdUI
// CSDN: https://blog.csdn.net/v_132
// QQ: 17379620

using AntdUI;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static Dictionary.ReferenceForm;
using ICell = NPOI.SS.UserModel.ICell;


namespace Dictionary
{
    public partial class UploadModel : AntdUI.Window
    {
        IniClass Ini = new IniClass();
        public UploadModel()
        {
            InitializeComponent();
            BindEventHandler();

        }
        /// <summary>
        /// 上传按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bn_sure_Click(object sender, EventArgs e)
        {
            try
            {
                List<string>List = new List<string>();

                DataTable ExcelReadDataTable = ReadExcel(targetPath);

                string read = ExcelReadDataTable.Rows[0].ItemArray[0].ToString();

                Ini.IniWriteValue("GI__Process", "GI__ProcessCount" , ExcelReadDataTable.Rows.Count.ToString());
                for (int i = 0; i < ExcelReadDataTable.Rows.Count; i++)
                {
                 
                    Ini.IniWriteValue("GI__Process", "GI__Process"+(i+1), ExcelReadDataTable.Rows[i][0].ToString());
                    List.Add(ExcelReadDataTable.Rows[i][0].ToString());
                }

                AntdUI.Message.success(this, "数据上传成功！", null, 2);
                //MessageBox.Show("数据上传成功");
                //this.Close();
              
                EventBus.PublishEvent(this, new DataTran(List));
            }
            catch (Exception ex)
            {
                AntdUI.Message.error(this, ex.Message, null, 3);
            }
        }

        private AntdUI.Window window;

        private void BindEventHandler()
        {
            window = this;
            //1.7.14开始,uploadDragger自带点击打开文件选择框
            uploadDragger.DragChanged += UploadDragger_DragChanged;
            uploadDragger.Multiselect = false;//允许多选文件
            uploadDragger.Filter = "Excel Files (*.xlsx;*.xls)|*.xlsx;*.xls";
            uploadDragger.HandDragFolder = true;//是否支持拖拽，默认为true

        }
        string targetPath = string.Empty;

        private void UploadDragger_DragChanged(object sender, AntdUI.StringsEventArgs e)
        {

            window = this;
            string[] filePaths = e.Value;
            foreach (string path in filePaths)
            {
                try
                {
                    // 获取源文件的文件名（含扩展名）
                    string fileName = Path.GetFileName(path);
                    uploadDragger.TextDesc = fileName;

                    // 构建目标路径（确保包含文件名）
                    string targetFolder = AppDomain.CurrentDomain.BaseDirectory + string.Format("ModelFiles\\");

                    targetPath = Path.Combine(targetFolder, fileName);

                    // 确保目标文件夹存在，不存在则创建
                    if (!Directory.Exists(targetFolder))
                    {
                        Directory.CreateDirectory(targetFolder);
                    }

                    // 复制文件（如果文件已存在，使用Overwrite参数覆盖）
                    File.Copy(path, targetPath, overwrite: true);
                    AntdUI.Message.info(window, "文件选择成功", autoClose: 3);
                }
                catch (Exception ex)
                {

                    AntdUI.Message.error(window, ex.Message, autoClose: 3);
                }

            }
        }

        /// <summary>
        /// 读取Excel文件内容并转换为DataTable
        /// </summary>
        /// <param name="filePath">Excel文件路径</param>
        /// <param name="sheetIndex">工作表索引（默认0，即第一个工作表）</param>
        /// <param name="hasHeader">是否包含表头（第一行为列名）</param>
        /// <returns>包含Excel数据的DataTable</returns>
        public DataTable ReadExcel(string filePath, int sheetIndex = 0, bool hasHeader = true)
        {
            // 验证文件是否存在
            if (!File.Exists(filePath))
            {
                throw new FileNotFoundException("Excel文件不存在", filePath);
            }

            // 根据文件扩展名判断Excel版本
            string fileExtension = Path.GetExtension(filePath).ToLower();
            if (fileExtension != ".xls" && fileExtension != ".xlsx")
            {
                throw new NotSupportedException("不支持的文件格式，仅支持.xls和.xlsx");
            }

            // 读取文件流
            using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                //// 创建工作簿对象
                //IWorkbook value = fileExtension switch
                //{
                //    ".xls" => new HSSFWorkbook(stream),  // 处理Excel 97-2003格式
                //    ".xlsx" => new XSSFWorkbook(stream), // 处理Excel 2007+格式
                //    _ => throw new NotSupportedException("不支持的Excel格式")
                //};

                IWorkbook value;
                switch (fileExtension)
                {
                    case ".xls":
                        value = new HSSFWorkbook(stream);  // 处理Excel 97-2003格式
                        break;
                    case ".xlsx":
                        value = new XSSFWorkbook(stream);  // 处理Excel 2007+格式
                        break;
                    default:
                        throw new NotSupportedException("不支持的Excel格式");
                }



                IWorkbook workbook = value;

                // 验证工作表索引
                if (sheetIndex < 0 || sheetIndex >= workbook.NumberOfSheets)
                {
                    throw new ArgumentOutOfRangeException(nameof(sheetIndex), "工作表索引超出范围");
                }

                // 获取指定工作表
                ISheet sheet = workbook.GetSheetAt(sheetIndex);
                if (sheet == null)
                {
                    throw new Exception("无法获取指定的工作表");
                }

                // 转换为DataTable
                return ConvertSheetToDataTable(sheet, hasHeader);
            }
        }

        /// <summary>
        /// 将工作表转换为DataTable
        /// </summary>
        private DataTable ConvertSheetToDataTable(ISheet sheet, bool hasHeader)
        {
            DataTable dataTable = new DataTable(sheet.SheetName);
            int startRowIndex = hasHeader ? 1 : 0; // 表头行索引（0开始）

            // 获取最大行和列索引
            int rowCount = sheet.LastRowNum;
            if (rowCount < 0) return dataTable; // 空表

            // 获取表头行
            IRow headerRow = hasHeader ? sheet.GetRow(0) : null;

            // 确定最大列数
            int maxColumnCount = 0;
            for (int i = 0; i <= rowCount; i++)
            {
                IRow row = sheet.GetRow(i);
                if (row != null && row.LastCellNum > maxColumnCount)
                {
                    maxColumnCount = row.LastCellNum;
                }
            }

            // 创建DataTable列
            for (int col = 0; col < maxColumnCount; col++)
            {
                string columnName = $"Column_{col + 1}"; // 默认列名

                // 如果有表头，使用表头单元格的值作为列名
                if (hasHeader && headerRow != null)
                {
                    ICell headerCell = headerRow.GetCell(col);
                    if (headerCell != null)
                    {
                        columnName = GetCellValue(headerCell).ToString();

                        // 处理空列名
                        if (string.IsNullOrWhiteSpace(columnName))
                        {
                            columnName = $"Column_{col + 1}";
                        }
                    }
                }

                // 处理重复列名
                if (dataTable.Columns.Contains(columnName))
                {
                    columnName = $"{columnName}_{col + 1}";
                }

                dataTable.Columns.Add(columnName);
            }

            // 填充数据行
            for (int rowIndex = startRowIndex; rowIndex <= rowCount; rowIndex++)
            {
                IRow row = sheet.GetRow(rowIndex);
                if (row == null) continue; // 跳过空行

                DataRow dataRow = dataTable.NewRow();
                bool isEmptyRow = true;

                // 读取每行的单元格值
                for (int colIndex = 0; colIndex < maxColumnCount; colIndex++)
                {
                    ICell cell = row.GetCell(colIndex);
                    object cellValue = GetCellValue(cell);

                    if (cellValue != null && !string.IsNullOrWhiteSpace(cellValue.ToString()))
                    {
                        isEmptyRow = false;
                    }

                    dataRow[colIndex] = cellValue ?? DBNull.Value;
                }

                // 跳过空行
                if (!isEmptyRow)
                {
                    dataTable.Rows.Add(dataRow);
                }
            }

            return dataTable;
        }

        /// <summary>
        /// 获取单元格的值（处理不同数据类型）
        /// </summary>
        private object GetCellValue(ICell cell)
        {
            if (cell == null) return null;

            switch (cell.CellType)
            {
                case CellType.String:
                    return cell.StringCellValue;

                case CellType.Numeric:
                    // 处理日期类型
                    if (DateUtil.IsCellDateFormatted(cell))
                    {
                        return cell.DateCellValue;
                    }
                    // 处理数字类型
                    return cell.NumericCellValue;

                case CellType.Boolean:
                    return cell.BooleanCellValue;

                case CellType.Formula:
                    // 处理公式（获取计算结果）
                    switch (cell.CachedFormulaResultType)
                    {
                        case CellType.String:
                            return cell.StringCellValue;
                        case CellType.Numeric:

                            if (DateUtil.IsCellDateFormatted(cell))
                            {
                                return cell.DateCellValue;
                            }
                            else
                            {
                                return cell.NumericCellValue;
                            }

                        case CellType.Boolean:
                            return cell.BooleanCellValue;
                        default:
                            return cell.CellFormula; // 无法计算时返回公式本身
                    }

                case CellType.Error:
                    return $"错误: {cell.ErrorCellValue}";

                default:
                    return null;
            }
        }

        private void bn_sure_Click_1(object sender, EventArgs e)
        {
            bn_sure_Click(sender, e);
        }
    }
}
